/*
 * @Date: 2023-11-7 15:15:32
 * @LastEditors: 老友  1527308832@qq.com
 * @LastEditTime: 2023-11-7 11:13:17
 * @FilePath: \cesium-tyro-blog\src\utils\Material\EllipsoidFadeMaterialProperty.js
 * @Description: 扩散圆材质
 */
import * as Cesium from "cesium";

export default class EllipsoidFadeMaterialProperty {
  constructor(options) {
    this._definitionChanged = new Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._time = new Date().getTime();
    this.color = options.color;
    this.duration = options.duration;
  }

  get isConstant() {
    return false;
  }

  get definitionChanged() {
    return this._definitionChanged;
  }

  getType(time) {
    return Cesium.Material.EllipsoidFadeMaterialType;
  }

  getValue(time, result) {
    if (!Cesium.defined(result)) {
      result = {};
    }

    result.color = Cesium.Property.getValueOrClonedDefault(
      this._color,
      time,
      Cesium.Color.WHITE,
      result.color
    );
    result.time =
      ((new Date().getTime() - this._time) % this.duration) / this.duration;
    return result;
  }

  equals(other) {
    return (
      this === other ||
      (other instanceof EllipsoidFadeMaterialProperty &&
        Property.equals(this._color, other._color))
    );
  }
}

Object.defineProperties(EllipsoidFadeMaterialProperty.prototype, {
  color: Cesium.createPropertyDescriptor("color"),
});

// Cesium.EllipsoidFadeMaterialProperty = EllipsoidFadeMaterialProperty;
Cesium.Material.EllipsoidFadeMaterialProperty = "EllipsoidFadeMaterialProperty";
Cesium.Material.EllipsoidFadeMaterialType = "EllipsoidFadeMaterialType";
Cesium.Material.EllipsoidFadeMaterialSource = `
  czm_material czm_getMaterial(czm_materialInput materialInput)
  {
    czm_material material = czm_getDefaultMaterial(materialInput);
    material.diffuse = 1.5 * color.rgb;
    vec2 st = materialInput.st;
    float dis = distance(st, vec2(0.5, 0.5));
    float per = fract(time);
    if(dis > per * 0.5){
      material.alpha = 0.0;
      discard;
    }else {
      material.alpha = color.a  * dis / per / 1.0;
    }
    return material;
  }
  `;

Cesium.Material._materialCache.addMaterial(
  Cesium.Material.EllipsoidFadeMaterialType,
  {
    fabric: {
      type: Cesium.Material.EllipsoidFadeMaterialType,
      uniforms: {
        color: new Cesium.Color(1.0, 0.0, 0.0, 1.0),
        time: 1,
      },
      source: Cesium.Material.EllipsoidFadeMaterialSource,
    },
    translucent: function (material) {
      return true;
    },
  }
);
